﻿/*******************************************************************************
 * Copyright © 2016 DJY 版权所有
 * Author: DJY
 * Description: 后台管理系统
 * Website：http://www.djyweb.cn
*********************************************************************************/
using DJY.Code;
using DJY.Service.WorkFlow;
using DJY.Domain.Entity.WorkFlow;
using DJY.Domain.ViewModel;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace DJY.Web.Areas.WorkFlow.Controllers
{
    public class WFDefController : ControllerBase
    {
        IWorkFlowEngine engine = OperatorProvider.Resolve<IWorkFlowEngine>();

        [HttpGet]
        
        public override ActionResult Index()
        {
            var user = OperatorProvider.GetCurrent();
            ViewBag.btns = engine.GetDefModuleButtons(user.UserId);
            return View();
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetTreeGridJson(string cateId,string keyword)
        {
            WFCategoryQueryInfo cateQueryInfo = new WFCategoryQueryInfo();
            string orgId = OperatorProvider.GetCurrent().CompanyId;
            cateQueryInfo.orgId = orgId;
            //cateQueryInfo.fDeleteMark = false;
            List<WorkFlowCategory> cateList = engine.CategoryList(cateQueryInfo);
            int id = 0;
            if(!string.IsNullOrEmpty(cateId))
            {
                int.TryParse(cateId, out id);
            }

            WFDefQueryInfo defQueryInfo = new WFDefQueryInfo();
            defQueryInfo.orgId = orgId;
            if (id > 0)
            {
                defQueryInfo.cateId = id;
            }

            defQueryInfo.keyword = keyword;
            List<WorkFlowDef> defList = engine.QueryFlow(defQueryInfo);
            if(defList != null)
            {
                List<int> cateIds = defList.Select(d => d.cateId).Distinct().ToList();
                defList.ForEach(d => { 
                    d.type = 2; 
                });
                List<WorkFlowCategory> defCates = cateList.Where(c => cateIds.Contains(c.id)).ToList();
                defList.AddRange(defCates.Select(c=>new WorkFlowDef
                { 
                    id = c.id.ToString(),
                    name = string.IsNullOrEmpty(c.parentName)?c.name:$"{c.parentName}-{c.name}",
                    cateId = 0,//c.parentId,
                    type = 1,
                    remark = c.remark,
                    deleteMark = c.deleteMark,
                    createTime = c.createTime,
                    createUser = c.createUser
                }));
            }

            var treeList = new List<TreeGridModel>();
            foreach (WorkFlowDef def in defList)
            {
                TreeGridModel treeModel = new TreeGridModel();
                bool hasChildren = defList.Any(c => c.cateId.ToString() == def.id);
                treeModel.id = def.id;
                treeModel.isLeaf = hasChildren;
                treeModel.parentId = def.cateId.ToString();
                treeModel.expanded = hasChildren;
                treeModel.entityJson = def.ToJson();
                treeList.Add(treeModel);
            }
            return Content(treeList.TreeGridJson());
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetFormJson(string keyValue)
        {
            string orgId = OperatorProvider.GetCurrent().CompanyId;
            WorkFlowDef def = null;
            if (!string.IsNullOrEmpty(keyValue))
            {
                List<WorkFlowDef> list = engine.QueryFlow(new WFDefQueryInfo { id = keyValue,orgId = orgId });
                if (list != null && list.Count > 0)
                {
                    def = list[0];
                }
            }

            if (def == null)
            {
                def = new WorkFlowDef();
            }

            return Json(def, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 我的流程
        /// </summary>
        public ActionResult MyFlow()
        {
            return View();
        }

        /// <summary>
        /// 流程实例
        /// </summary>
        public ActionResult MyFlowList()
        {
            var user = OperatorProvider.GetCurrent();
            return Json(engine.MyFlowList(user?.UserId),JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 流程实例
        /// </summary>
        public ActionResult StartFlow(string id)
        {
            var user = OperatorProvider.GetCurrent();
            return Json(engine.StartFlow(id, user?.UserId), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 流程实例
        /// </summary>
        public ActionResult StopFlow(string id)
        {
            var user = OperatorProvider.GetCurrent();
            return Json(engine.StopFlow(id, user?.UserId), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 催办
        /// </summary>
        public ActionResult AddWeight(string id)
        {
            var user = OperatorProvider.GetCurrent();
            return Json(engine.AddWeight(id, user?.UserId), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 流程实例
        /// </summary>
        [HandlerAjaxOnly]
        [HttpPost]
        public ActionResult FlowList(WFInstanceQueryInfo queryInfo)
        {
            var user = OperatorProvider.GetCurrent();
            queryInfo.userId = user.UserId;
            queryInfo.isSys = user.IsSystem;
            queryInfo.orgId = user.CompanyId;
            return Json(engine.QueryFlow(queryInfo));
        }

        /// <summary>
        /// 流程实例流转信息
        /// </summary>
        public ActionResult FlowNodeList(string id)
        {
            return Json(engine.FlowNodeList(id),JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        [HandlerAjaxOnly]
        [AjaxValidateAntiForgeryToken]
        public ActionResult SubmitForm(WorkFlowDef def)
        {
            var user = OperatorProvider.GetCurrent();
            def.createUser = user.UserId;
            def.lastUpdateUser = user.UserId;
            def.orgId = user.CompanyId;
            EditItemResult result = engine.Save(def);
            if(result.result)
            {
                return Success("操作成功。",null);
            }
            else
            {
                return Error(result.msg);
            }
        }

        [HttpPost]
        [HandlerAjaxOnly]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteForm(string ids,bool state)
        {
            var user = OperatorProvider.GetCurrent();
            if (user == null)
            {
                return new HttpStatusCodeResult(System.Net.HttpStatusCode.Unauthorized);
            }

            if(string.IsNullOrEmpty(ids))
            {
                return Error("缺少必要参数");
            }

            List<string> idList = ids.Split(new char[] { ','},System.StringSplitOptions.RemoveEmptyEntries).ToList();
            EditItemResult result = engine.DeleteFlow(idList, state, user.UserId);
            if (result.result)
            {
                return Success("操作成功。",null);
            }
            else
            {
                return Error(result.msg);
            }
        }

        [HttpPost]
        [HandlerAjaxOnly]
        
        [ValidateAntiForgeryToken]
        public ActionResult Remove(string ids)
        {
            var user = OperatorProvider.GetCurrent();
            if (user == null)
            {
                return new HttpStatusCodeResult(System.Net.HttpStatusCode.Unauthorized);
            }

            if (string.IsNullOrEmpty(ids))
            {
                return Error("缺少必要参数");
            }

            List<string> idList = ids.Split(new char[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries).ToList();
            EditItemResult result = engine.RemoveFlow(idList, user.UserId);
            if (result.result)
            {
                return Success("操作成功。",null);
            }
            else
            {
                return Error(result.msg);
            }
        }

        [HttpPost]
        [HandlerAjaxOnly]
        
        [ValidateAntiForgeryToken]
        public ActionResult Publish(string ids)
        {
            var user = OperatorProvider.GetCurrent();
            if (user == null)
            {
                return new HttpStatusCodeResult(System.Net.HttpStatusCode.Unauthorized);
            }

            if (string.IsNullOrEmpty(ids))
            {
                return Error("缺少必要参数");
            }

            List<string> idList = ids.Split(new char[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries).ToList();
            EditItemResult result = engine.Publish(idList, user.UserId);
            if (result.result)
            {
                return Success("操作成功。", null);
            }
            else
            {
                return Error(result.msg);
            }
        }
    }
}
